package com.gyg.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.json.JSONUtil;
import com.gyg.client.CloudUserClient;
import com.gyg.constant.RedisConstants;
import com.gyg.domain.CloudUser;
import com.gyg.enums.SessionEnum;
import com.gyg.returns.RespCode;
import com.gyg.returns.RespEntity;
import com.gyg.returns.RespTable;
import com.gyg.utils.OSSUtil;
import com.gyg.utils.RedisUtil;
import com.gyg.vo.param.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 短信验证码表 前端控制器
 * </p>
 *
 * @author gyg
 * @since 2021-02-20
 */
@RestController
@RequestMapping("/cloud-user")
@Slf4j
@Api(value = "用户模块", tags = "用户模块")
public class CloudUserController {

    @Resource
    private CloudUserClient cloudUserClient;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    @ApiOperation(value = "用户登陆")
    public RespEntity<CloudUser> login(LoginParam loginParam, HttpSession session) {
        //校验验证码
        String oldCode = redisUtil.get(RedisConstants.key.getSms(loginParam.getMobile()));
        log.info("oldCode = {}, userCode = {}", oldCode, loginParam.getCode());
        if (! StringUtils.equals(loginParam.getCode(), oldCode)) {
            return new RespEntity(RespCode.CODE_ERROR);
        }
        //校验账号密码
        RespEntity<CloudUser> respEntity = cloudUserClient.login(loginParam);
        if (Objects.isNull(respEntity.getData())) {
            return new RespEntity(RespCode.LOGIN_ERROR);
        }
        Map<String, Object> map = (Map<String, Object>) respEntity.getData();
        CloudUser cloudUser = JSONUtil.toBean(JSONUtil.toJsonStr(map), CloudUser.class);
        //校验封禁
        if (!cloudUser.getBan().equals(0)) {
            return new RespEntity<>(RespCode.IS_BAN);
        }
        //校验管理员权限
        if (!cloudUser.getAdmin().equals(1)) {
            return new RespEntity<>(RespCode.NOT_ADMIN);
        }
        session.setAttribute(SessionEnum.USER.getCode(), cloudUser);
        return new RespEntity(RespCode.SUCCESS);
    }

    @GetMapping("/welcome")
    @ApiOperation(value = "首页欢迎语")
    public RespEntity welcome(HttpSession session) {
        CloudUser cloudUser = (CloudUser) session.getAttribute(SessionEnum.USER.getCode());
        RespEntity respEntity = cloudUserClient.userInfo(cloudUser.getId());
        return respEntity;
    }

    @DeleteMapping("/exit")
    @ApiOperation(value = "退出登录")
    public RespEntity exitLogin(HttpSession session) {
        session.removeAttribute(SessionEnum.USER.getCode());
        return new RespEntity(RespCode.SUCCESS);
    }

    @GetMapping("/list")
    @ApiOperation(value = "用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "page", value = "当前页数", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "limit", value = "每页数量", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "column", value = "字段名", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "limit", value = "字段值", required = false)
    })
    public RespTable cloudUserList(@RequestParam(value = "page", required = true) Integer page,
                                   @RequestParam(value = "limit", required = true) Integer limit,
                                   @RequestParam(value = "column", required = false) String column,
                                   @RequestParam(value = "value", required = false) String value) {
        RespTable<List<CloudUser>> respTable = cloudUserClient.queryAllUser(page, limit, column, value);
        return respTable;
    }

    @PutMapping("/ban")
    @ApiOperation(value = "封禁用户")
    @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "userId", value = "用户id", required = true)
    public RespEntity cloudUserBan(@RequestParam(value = "userId", required = true) Integer userId) {
        RespEntity respEntity = cloudUserClient.cloudUserBan(userId);
        return respEntity;
    }

    @PutMapping("/deBlock")
    @ApiOperation(value = "解封用户")
    @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "userId", value = "用户id", required = true)
    public RespEntity cloudUserDeBlock(@RequestParam(value = "userId", required = true) Integer userId) {
        RespEntity respEntity = cloudUserClient.cloudUserDeBlock(userId);
        return respEntity;
    }

    @GetMapping("/banList")
    @ApiOperation(value = "用户黑名单")
    public RespTable cloudUserBanList(PageParam pageParam) {
        RespTable respTable = cloudUserClient.cloudBanUserList(pageParam);
        return respTable;
    }

    @GetMapping("/exportExcel")
    @ApiOperation(value = "批量导出Excel")
    public void exportExcel(Integer[] ids, HttpServletResponse response) throws Exception {
        RespEntity<List<CloudUser>> respEntity = cloudUserClient.queryUserByIds(ids);
        List<CloudUser> userList  = (List<CloudUser>) respEntity.getData();
        ExportParams exportParams = new ExportParams("用户数据信息", "用户");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, CloudUser.class, userList);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-disposition","attachment;filename=user_"+new Date().getTime()+".xls");
        workbook.write(response.getOutputStream());
    }

    @GetMapping("/exportExcelAll")
    @ApiOperation(value = "全部导出Excel")
    public void exportExcelAll(HttpServletResponse response) throws IOException {
        RespEntity<List<CloudUser>> respEntity = cloudUserClient.queryAllUser();
        List<CloudUser> userList = (List<CloudUser>) respEntity.getData();
        ExportParams exportParams = new ExportParams("用户数据信息", "用户");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, CloudUser.class, userList);
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-disposition","attachment;filename=user_"+new Date().getTime()+".xls");
        workbook.write(response.getOutputStream());
    }

    @GetMapping("/sex")
    @ApiOperation(value = "用户性别统计")
    public RespEntity sexCount() {
        RespEntity respEntity = cloudUserClient.cloudUserSex();
        return respEntity;
    }

    @GetMapping("/chinaMap")
    @ApiOperation(value = "登陆用户地区分布-中国地图")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "beginDate", value = "开始时间", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "endDate", value = "结束时间", required = false)
    })
    public RespEntity chinaMap(@RequestParam(value = "beginDate", required = false) String beginDate,
                               @RequestParam(value = "endDate", required = false) String endDate) {
        RespEntity respEntity = cloudUserClient.chinaMap(beginDate, endDate);
        return respEntity;
    }

    @GetMapping("/provinceMap")
    @ApiOperation(value = "登陆用户地区分布-省份地图")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "province", value = "省份名称", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "beginDate", value = "开始时间", required = false),
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "endDate", value = "结束时间", required = false)
    })
    public RespEntity provinceMap(@RequestParam(value = "province", required = true) String province,
                                  @RequestParam(value = "beginDate", required = false) String beginDate,
                                  @RequestParam(value = "endDate", required = false) String endDate) {
        RespEntity respEntity = cloudUserClient.provinceMap(province, beginDate, endDate);
        return respEntity;
    }

}
